package com.shuda.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuda.business.user.entity.TenantEntity;
import com.shuda.business.user.mapper.TenantMapper;
import com.shuda.business.user.service.TenantService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.security.SecurityUtils;
import com.shuda.common.utils.PageResult;
import com.shuda.common.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 租户服务实现类
 */
@Service
@RequiredArgsConstructor
public class TenantServiceImpl implements TenantService {

    private final TenantMapper tenantMapper;

    @Override
    public PageResult<TenantEntity> getTenantPage(PageDTO pageDTO, QueryWrapper<TenantEntity> queryWrapper) {
        Page<TenantEntity> page = PageUtils.buildPage(pageDTO);
        Page<TenantEntity> tenantPage = tenantMapper.selectPage(page, queryWrapper);
        return PageUtils.buildPageResult(tenantPage);
    }

    @Override
    public TenantEntity getById(Long id) {
        return tenantMapper.selectById(id);
    }

    @Override
    public TenantEntity getByTenantCode(String tenantCode) {
        QueryWrapper<TenantEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_code", tenantCode);
        return tenantMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTenant(TenantEntity tenant) {
        // 检查租户编码是否已存在
        if (getByTenantCode(tenant.getTenantCode()) != null) {
            throw new BusinessException("租户编码已存在");
        }
        
        // 设置默认状态
        if (tenant.getStatus() == null) {
            tenant.setStatus("active");
        }
        
        // 设置创建/更新信息
        tenant.setCreatedTime(LocalDateTime.now());
        tenant.setCreator(SecurityUtils.getCurrentUserId());
        tenant.setUpdatedTime(LocalDateTime.now());
        tenant.setUpdater(SecurityUtils.getCurrentUserId());
        tenant.setDelFlag("0");
        
        tenantMapper.insert(tenant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTenant(TenantEntity tenant) {
        // 检查租户是否存在
        TenantEntity existingTenant = tenantMapper.selectById(tenant.getId());
        if (existingTenant == null) {
            throw new BusinessException("租户不存在");
        }
        
        // 如果更新租户编码，需要检查是否已存在
        if (tenant.getTenantCode() != null && !tenant.getTenantCode().equals(existingTenant.getTenantCode())) {
            QueryWrapper<TenantEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenant_code", tenant.getTenantCode());
            if (tenantMapper.selectCount(queryWrapper) > 0) {
                throw new BusinessException("租户编码已存在");
            }
        }
        
        // 设置更新信息
        tenant.setUpdatedTime(LocalDateTime.now());
        tenant.setUpdater(SecurityUtils.getCurrentUserId());
        
        tenantMapper.updateById(tenant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTenant(Long id) {
        TenantEntity tenant = tenantMapper.selectById(id);
        if (tenant == null) {
            throw new BusinessException("租户不存在");
        }
        
        // 逻辑删除
        tenant.setDelFlag("1");
        tenant.setUpdatedTime(LocalDateTime.now());
        tenant.setUpdater(SecurityUtils.getCurrentUserId());
        tenantMapper.updateById(tenant);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTenants(List<Long> ids) {
        for (Long id : ids) {
            deleteTenant(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTenantStatus(Long id, String status) {
        TenantEntity tenant = tenantMapper.selectById(id);
        if (tenant == null) {
            throw new BusinessException("租户不存在");
        }
        
        tenant.setStatus(status);
        tenant.setUpdatedTime(LocalDateTime.now());
        tenant.setUpdater(SecurityUtils.getCurrentUserId());
        tenantMapper.updateById(tenant);
    }

    @Override
    public TenantEntity getTenantConfig(Long id) {
        return tenantMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTenantConfig(Long id, TenantEntity config) {
        TenantEntity tenant = tenantMapper.selectById(id);
        if (tenant == null) {
            throw new BusinessException("租户不存在");
        }
        
        // 只更新配置相关字段
        tenant.setMaxUsers(config.getMaxUsers());
        tenant.setMaxCustomers(config.getMaxCustomers());
        tenant.setMaxChannels(config.getMaxChannels());
        tenant.setMaxSchemes(config.getMaxSchemes());
        tenant.setConfigJson(config.getConfigJson());
        tenant.setUpdatedTime(LocalDateTime.now());
        tenant.setUpdater(SecurityUtils.getCurrentUserId());
        
        tenantMapper.updateById(tenant);
    }
}